<?php
class PublicController extends BaseController {
	public function _initialize() {
		parent::_initialize();
		$this->db = model('User');
	}
	/**
     * 验证码
     */
    public function verify() {
        libfile('Verify');
        ob_clean();
        $verify = new Verify($width=90,$height=45,$fontSize=14);
        $verify->doimage();//sesssion('verify);
    }
    /**
     * [qr description]
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
	public function qr($invite_code){
		libfile('phpqrcode');
		$Qrcode = new \QRcode;
		// $data=C("site_companyurl")."/reg.php?u=".$uid;
		// $data='http://'.$_SERVER['HTTP_HOST']."/reg.php?u=".$invite_code;
		//$data=C("site_companyurl")."/reg.php?u=".$invite_code;
		$data=C("site_companyurl")."/index.php?m=user&c=public&a=register&u=".$invite_code;
		// $data=C("site_companyurl")."/register.php?u=".$invite_code;
		$errorLevel = "L";
		//定义生成图片宽度和高度;默认为3
		$size = "10";
		//定义生成内容
		$content = urldecode($data);
		//调用QRcode类的静态方法png生成二维码图片//
		$Qrcode->png($content, false, $errorLevel, $size,1);
	}
	// public function login() {
	// 	$this->userid = (int) authcode(cookie('user_key'), 'DECODE', C('site_key'));
	// 	if ($this->userid>0) {
	// 		header('Location:'.U('Index/index'));//跳转到我的新域名地址
	// 		exit;
	// 	}
	// 		if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') != false ){
	// 	    	libfile('Wechat');//将Wechat类文件加载进来
	// 	    	$options=array();
	// 		    $options['token']=C('weixin_token');
	// 		    $options['encodingAesKey']=md5(C('weixin_token'));
	// 		    $options['appid']=C('appid');
	// 		    $options['appsecret']=C('appsecret');
	// 		    $weObj=new Wechat($options);
    //             if($_GET['bind']){
    //             	 if (!isset($_GET['code'])){
    //             	 	$redirectUrl = 'http://'.$_SERVER['HTTP_HOST'].U('login',array('bind'=>'account'));
    //                     $url = $weObj->getOauthRedirect($redirectUrl,1,'snsapi_base');
    //                     Header("Location: $url");
    //             	 }else{
    //             	 	$userinfo =$weObj->getOauthAccessToken();
    //                     $_GET['wechat_openid'] = authcode($userinfo['openid'],'ENCODE');
    //             	 }
    //             }
    //         }	
	// 		// 第三方登录配置信息
	// 		$logins = getcache('login','site');
	// 		if(ACTION_NAME=="logincompay"){
	// 			$SEO=seo(0,"商家登录");
	// 			include template('logincompay');
	// 		}else{
	// 			$SEO=seo(0,"用户登录");
	// 			include template('login');
	// 		}
	// }
	
	//登录
	public function login()
	{	
		// if(is_login()>0){
		// 	header('Location:'.U('Index/index'));
		// 	exit;
		// }
		// if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') != false ){//微信内置浏览器登录

		// }
		if(IS_POST){
			$param = I('post.');
			if(!isset($param['username']) || empty($param['username']) || !isset($param['password']) || empty($param['password'])) showmessage('请填写用户名和手机号');
			if(!is_mobile($param['username'])) showmessage('请填写正确格式的手机号');
			$find = M('user')->where(['username'=>$param['username']])->find();
			if(!$find) showmessage('该账号还没有注册');
			switch($find['status']){
				case 2;
					showmessage('该账号已被冻结');
					break;
				case 3;
					showmessage('该账号已被禁止');
					break;
				case 4;
					showmessage('该账号已被删除');
					break;
				default:
					if(md5($find['salt'].$param['password']) != $find['password']) showmessage('密码错误');
					session('username',$param['username']);
					session('id',$find['id']);
					cookie('user_key',authcode('1','ENCODE'));
					// echo json_encode(['msg'=>'登录成功，稍后将跳转到交易首页','status'=>1]);
					showmessage('登录成功，稍后将跳转到交易首页',U('/user/trade/index?type=buy'),3);
			}
		}else{
			include template('login');
		}
	}

	/**
	 * 会员注册
	 */
	public function register() {

		
		$username = isset($_POST['username']) ? trim($_POST['username']) : '';
		
		if(IS_POST){
		
			$param = I('post.');
			
			if(!$this->db->create($param)) showmessage($this->db->getError());
			// die;
			session("verify",null);
			if($param['invite_code'] != ''){
				$find = M('user')->where(['invite_code'=>strtoupper($param['invite_code'])])->find();
				if(!$find) showmessage('该邀请码不存在，请重新填写');
				$param['refer_id'] = $find['id'];
			}
			unset($param['verify']);
			unset($param['confirm_password']);
			unset($param['confirm_pay_password']);
			//生成自己的邀请码
			$refer_info = M('user')->where(['invite_code'=>$param['invite_code']])->field('id,refer_id,all_head,one,two,three')->find();
			$param['refer_id'] = $refer_info['id'];
			$param['register_time'] = date('Y-m-d H:i:s');
			$param['all_head'] = $refer_info['all_head'] == '' ? ','.$refer_info['id'].',' : $refer_info['all_head'].$refer_info['id'].',';
			
			$param['invite_code'] = $this->createInviteCode();
			
			$param['salt'] = random(10);
			//登录密码
			$param['password'] = md5($param['salt'].$param['password']);
			//交易密码
			$param['pay_password'] = md5($param['salt'].$param['pay_password']);
			try{
				$insert_id = $this->db->add($param);
				//更新自己的上级
				$one_info = [
					'one'=> $refer_info['one'] ? $refer_info['one'].$insert_id.',' : ','.$insert_id.',',
				];
				M('user')->where(['id'=>$refer_info['id']])->save($one_info);
				//更新上上级
				$find_two = M('user')->where(['id'=>$refer_info['refer_id']])->field('id,refer_id,one,two,three,all_head')->find();
				if($find_two){
					$two_info = [
						'two'=> $find_two['two'] ? $find_two['two'].$insert_id.',' : ','.$insert_id.',',
					];
					M('user')->where(['id'=>$find_two['id']])->save($two_info);
					//更新上上上级
					$find_three = M('user')->where(['id'=>$find_two['refer_id']])->field('id,refer_id,two,three,all_head,one')->find();
					if($find_three){
						$three_info = [
							'three'=> $find_three['two'] ? $find_three['two'].$insert_id.',' : ','.$insert_id.',',
						];
						M('user')->where(['id'=>$find_two['id']])->save($two_info);
					}
				}
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}
			showmessage("$username",'goback',1);//identityAuthentication
			
		}else{
			$invite_code = isset($_GET['invite_code']) && $_GET['invite_code'] ? $_GET['invite_code'] : '';
			include template('register');
		}
	}



	//忘记密码
	public function forget_password()
	{
		if(IS_POST){
			$param = I('post.');
			
			if(empty($param['sms_code']) || empty($param['username']) || empty($param['password'])) showmessage('短信验证码，手机号，新密码都不能为空');
			if(!is_mobile($param['username'])) showmessage('请填写正确格式的手机号');
			if(session('reg_code_time')+ 120 < time()) showmessage('短信验证码已经过期');
			// var_dump($param['sms_code']);
			// var_dump(session('reg_code'));
			// var_dump($param['username']);
			// var_dump(session('mobile'));
			// die;
			if($param['sms_code'] != session('reg_code')  || $param['username'] != session('mobile')) showmessage('手机号跟验证码不匹配');
			
			session("reg_code",null);
			session('username',NULL);
			//只要发送过验证码就证明该账号已经注册过并且没有被封
			// $find = M('user')->where(['username'=>$param['username']])->find();
			// if(!$find) error(['msg'=>'该手机号还没有注册']);
			$find = M('user')->where(['username'=>$param['username']])->field('id,username,salt')->find();
			if(!$find) showmessage('该手机号还没有注册');
			try{
				M('user')->where(['username'=>$param['username']])->save(['password'=>md5($find['salt'].$param['password'])]);
				session('send_code_time',NULL);
			}catch(\Exception $e){
				showmessage($e->getMessage());
			}
			showmessage('重置密码成功',U('/user/public/login'),1);
		}else{
			include template('forget_password');
		}
	}


	
	//实名认证
	public function identityAuthentication()
	{
		
	}

	public function logout() {
		// $this->userid = (int) authcode(cookie('user_key'), 'DECODE', C('site_key'));
		// $this->userinfo = getUserInfo();
		$url=U('Public/login');
		$_SESSION['id'] = "";
		cookie('_uname', null);
		cookie('user_key', null);
		$_SESSION["pinpass"]="";
		$_SESSION["lasttime"]="";
		$_SESSION["admins"]="";
		runhook('user_logout_success');
		redirect($url);
	}

	private function createInviteCode()
	{
		$str = '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ';
		$str_length = strlen($str);
		$return ='';
		for($i = 0;$i< 6;$i++){
			$return .= strtoupper(substr($str,mt_rand(0,$str_length-1),1));
		}
		$find = M('user')->where(['invite_code'=>$return])->field('id,username,invite_code')->find();
		if($find){
			return $this->createInviteCode();
		}
		return $return;
	}

	/**
	 * 会员注册
	 */
	public function mobileinvite() {
		if(IS_POST){
			$param = $_POST;
			if (!is_mobile($param['mobile_phone'])) showmessage('手机号格式错误');
			if (empty($param['mobi_code'])) showmessage('验证码不能为空');
			if (empty($param['password'])) showmessage('登录密码不能为空');
			if (empty($param['pinpass'])) showmessage('支付密码不能为空');
			if (!is_numeric($param['pinpass']) || strlen($param['pinpass'])!=6) showmessage('支付密码为6位数字');
			// if( $param['imgcode'] != $_SESSION["reg_code"]){
			// 	showmessage('图形验证码错误');
			// }			
			if( $param['mobi_code'] != $_SESSION["reg_code"]){
				showmessage('验证码错误');
			}
			session("reg_code",null);
			session("verify",null);
			$register = array();
			$register['username']     = trim($param['username']);
			$register['mobile_phone'] = trim($param['mobile_phone']);
			if (!preg_match('/^[A-Za-z0-9_\x{4e00}-\x{9fa5}]+$/u', $register['username'])) {
				showmessage('用户名由2-16位数字或字母、汉字、下划线组成！');
			}
			$conunt = (int) M("user")->where("username=".$register['username'].' OR mobile_phone = '.$register['mobile_phone'])->count();
			if($conunt > 0){
				showmessage('用户名或手机号已被占用！');
			}
			/////////////////////////////////////
			//邀请人信息/
			//优先使用表单提交yid 没有取cookie
			/////////////////////////
			$y_name=$param['y_name'];
			if($y_name!=''){
				$ymap['invite_code']=strtoupper($y_name);
				$invite_user=M("user")->where($ymap)->find();
				unset($ymap);
			}else{
				$y_id=(intval(cookie("yid"))>0)?intval(cookie("yid")):intval($_GET['u']);
				$invite_user=M("user")->where("id=".$y_id)->find();
			}
			if($invite_user){
		        if($invite_user['invite_str']!=""){
		            $register['invite_str'] = $invite_user['invite_str'].$invite_user['id'].",";
		        }else{
		            $register['invite_str'] = ",".$invite_user['id'].",";
		        }
		        $register['invite_id'] = $invite_user['id'];
			}
			$register['valid']    = random(10);
			$register['password'] = $param['password'] ? md5($register['valid'].$param['password']) : false;
			// $register['userpassword2']=md5($register['valid'].$param['password']);
			$register['pinpass'] = md5($param["pinpass"]);
			$register['invite_code'] = strtoupper(shorturl($register['username'])[0]);
			//p($register);exit;
			$register['user_type'] = 1;
			$result = $this->db->update($register);
			if($result){
				// 更新联盟人数
				updateInviteAllCount($register['invite_str']);
				session('reg_code', null);
				// $this->putlogin($result, $param['username']);
				// runhook('n_reg_success',array('user_id'=>$result));
				// runhook('user_login_success');
				showmessage('注册成功,将跳转到会员中心',"",1);
			}else{
				showmessage($this->db->getError());
			}
		} 
	}

	/**
	 * 会员注册
	 */
	public function reg() {
		$_SESSION["send_code_time"]=random(10);
		// if (is_login()>0) {
		// 	redirect(U("User/Index/index"));
		// }
		// 	if (is_login()>0) {
		// 	redirect(U("User/trade/index"));
		// }
		if(session('id')){
			redirect(U("User/trade/index"));
		}
		$logins = getcache('login','site');
		$yid =  intval($_GET['u']);
		if($yid > 0){
			cookie("yid",$yid);
			// $_SESSION['u'] = $yid;
		} else {
			if(cookie('yid')) $yid = intval(cookie('yid'));
		}
		$yinfo = $this->db->field("id,mobile_phone,username,invite_code")->where(array('id'=>$yid))->find();
		// p($yinfo);
		// p($_SESSION);
		// $SEO = seo(0, '用户注册');
		// include template('reg');
		//include template('register');
	}


	/**
	 * 会员注册 扫码跳转的注册页面
	 */
	public function invite() {
		$_SESSION["send_code_time"]=random(10);
		$logins = getcache('login','site');

		$invite_code =  $_GET['u'];
		if($invite_code !="" ){
			cookie("yid",$invite_code);
			// $_SESSION['u'] = $yid;
		} else {
			if(cookie('yid')) $yid = intval(cookie('yid'));
		}
		// $yinfo = $this->db->field("id,mobile_phone,username,invite_code")->where(array('id'=>$yid))->find();

		$SEO = seo(0, '用户注册');
		include template('invitereg');
	}






	public function forget(){
		if(IS_POST){
			$param = $_POST;
			if (!is_mobile($param['mobile_phone'])) showmessage('手机号格式错误');
			if (empty($param['mobi_code'])) showmessage('验证码不能为空');
			if (empty($param['password'])) showmessage('登录密码不能为空');
			if( $param['mobi_code'] != $_SESSION["reg_code"]){
				showmessage('验证码错误');
			}
			session("reg_code",null);
			session("verify",null);
			$mobile_phone = trim($param['mobile_phone']);
			$map['username|mobile_phone'] = $mobile_phone;
			$user = M("user")->where($map)->find();
			if($user['id']>0){
				$data = array();
				$data['id'] = $user['id'];
				$data['valid']    = random(10);
				$data['password'] = $param['password'] ? md5($data['valid'].$param['password']) : false;
				$rut = M("user")->save($data);
				if($rut) showmessage('密码已经成功更改！',"",1);
			}
			showmessage('找回密码失败！');
		}
		$_SESSION["send_code_time"]=random(10);
		$SEO = seo(0, '忘记密码');
		include template('forget');
	}


	//发送短信验证码
	public function send_code() {
		// if($_GET["token"]!=$_SESSION["send_code_time"]){
		// 	echo  1;
		// 	$json["status"] = 1;
		// 	$json["info"] = "已经发送至您的" . $_GET["mobile"] . "的手机中！";//{$_SESSION['send_code_time']}";
		// 	exit(json_encode($json));die;
		// }
		// if($_SESSION["send_code_time"]==""){
		// 	echo 2;
    	// 	$json["status"] = 1;
		// 	$json["info"] = "已经发送至您的号码为：" . $_GET["mobile"] . "的手机中!2";
		// 	exit(json_encode($json));die;
		// }
        if (isset($_SESSION['reg_code_time']) && time() - $_SESSION['reg_code_time'] < 10) {
            $json['status'] = 0;
            $json['info'] = '您的操作过于频繁，请稍后重试。';
            die(json_encode($json));
            die;
        }
        // 验证码类型 类型为空的不发送
        $typeArr = array("reg","repass","forget","trade");
        // p($typeArr);
        if(!in_array($_GET["type"],$typeArr)){
            $json['status'] = 0;
            $json['info'] = '发送失败，请稍后重试。';
            die(json_encode($json));
            die;
        }
		if($_GET["type"]=="reg" ){
			$token = $_GET['code'];
			if (empty($token)) {
				$json["status"] = 0;
				$json["info"]   = "请填写图形验证码！";
				exit(json_encode($json));die;
			}
	        $tokenAuthAcess = strtolower($token);
			if($tokenAuthAcess!= $_SESSION["verify"]){
				$json["status"] = 0;
				$json["info"] = "图形验证码验证错误！";
				exit(json_encode($json));die;
			}
			$conunt=M("user")->where("mobile_phone=".$_GET['mobile'])->count();
			if($conunt>0){
				$json['status'] = 0;
				$json['info'] = '您的手机号码已经注册过了。';
				die(json_encode($json));
				die;	
			}
		}
		if($_GET["type"]=="forget" ){
			$token = $_GET['code'];
			// if (empty($token)) {
			// 	$json["status"] = 0;
			// 	$json["info"]   = "请填写图形验证码！";
			// 	exit(json_encode($json));die;
			// }
	        // $tokenAuthAcess = strtolower($token);
			// if($tokenAuthAcess!= $_SESSION["verify"]){
			// 	$json["status"] = 0;
			// 	$json["info"] = "图形验证码验证错误！";
			// 	exit(json_encode($json));die;
			// }
			$conunt=(int)M("user")->where("username=".$_GET['mobile'])->count();
			if($conunt==0){
				$json['status'] = 0;
				$json['info'] = '您的手机号码不正确。';
				die(json_encode($json));
				die;	
			}
		}
		if($_GET["type"]=="repass" ){
			$token = $_GET['code'];
			if (empty($token)) {
				$json["status"] = 0;
				$json["info"]   = "请填写图形验证码！";
				exit(json_encode($json));die;
			}
	        $tokenAuthAcess = strtolower($token);
			if($tokenAuthAcess!= $_SESSION["verify"]){
				$json["status"] = 0;
				$json["info"] = "图形验证码验证错误！";
				exit(json_encode($json));die;
			}
			$this->user_info = getUserInfo();
			$_GET['mobile'] = $this->user_info['mobile_phone'];
			if($_GET['mobile']==""){
				$json["status"] = 0;
				$json["info"] = "发送失败，请稍后重试。";
				exit(json_encode($json));die;				
			}
		}
		if($_GET["type"]=="trade" ){
			// $token = $_GET['code'];
			// if (empty($token)) {
			// 	$json["status"] = 0;
			// 	$json["info"]   = "请填写图形验证码！";
			// 	exit(json_encode($json));die;
			// }
			// $tokenAuthAcess = strtolower($token);
			// if($tokenAuthAcess!= $_SESSION["verify"]){
			// 	$json["status"] = 0;
			// 	$json["info"] = "图形验证码验证错误！";
			// 	exit(json_encode($json));die;
			// }
			$this->user_info = getUserInfo();
			$_GET['mobile'] = $this->user_info['mobile_phone'];
			if($_GET['mobile']==""){
				$json["status"] = 0;
				$json["info"] = "发送失败，请稍后重试。";
				exit(json_encode($json));die;				
			}
		}
		if (empty($_GET['mobile']) || strlen($_GET['mobile']) != 11) {
			die;
        }
		$code = rand(10000, 99999);
		session('reg_code', $code);
		$content = '您的验证码为：' . $code . '请于2分钟内完成验证';
		$sendRs = sendsms(I('mobile'), $content);
		if($_GET['mobile']==""){
            $json['status'] = 0;
            $json['info'] = '发送失败！';
            die(json_encode($json));
		}
		// var_dump($sendRs);
        if ($sendRs === true) {
			// echo 1;
			session('send_code_time',time());
			session('reg_code_time', time());
			session('mobile',$_GET['mobile']);
            $json['status'] = 1;
            $json['info'] = '已经发送至您的号码为：' . $_GET['mobile'] . '的手机!';
            die(json_encode($json));
        } else {
            $json['status'] = 0;
            $json['info'] = empty($sendRs) ? '发送失败！' : $sendRs;
            die(json_encode($json));
        }
	}
	/**
	 * 
	 * 验证注册
	 */
	public function checkReg() {
		if (C('reg_isreg') != 1) {//判断是否允许注册
			echo '非法操作！';
			exit;
		}
		$userModel = model('User');
		if (C('reg_regvalidation') == 0) {//是否需要验证
			$_POST['status'] = 1; //不需要验证，用户状态设置为1 表示可以使用
			$valiStats = false;
		} else {
			$_POST['status'] = 0; //表示未验证
			$valiStats = true;
		}
		$_POST['pay_points'] = C('reg_regintegral'); //赠送的积分
		$res = $userModel->create();
		if (!$res) {//字段验证失败
			echo $userModel->getError();
			exit;
		}
		$uid = $userModel->add();
		if ($uid <= 0) {
			echo '注册失败！';
		} else {
			if ($valiStats) {//需要验证
			} else {
				if (C('reg_regcoupons') != 0) {//赠送优惠券
					//赠送优惠劵流程
					$this->zsj($uid); //这个自己写
				}
				$userInf = array('uid' => $uid, 'uname' => $this->_post('user_name'),'ico'=>'');
				$this->loginOk($userInf);
			}
		}
	}
	
	/**
	 * 
	 * 使用AJAX判断字段唯一性
	 */
	public function ajaxCheckKey() {
		$val = $this->_post('param'); //值
		$key = $this->_post('name'); //键
		if($key == 'username'){
			if(is_numeric($val)){
				echo '{"info":"用户名不能为纯数字","status":"n"}';
				return false;
			}
			if(is_email($val)){
				echo '{"info":"邮箱不能作为用户名","status":"n"}';
				return false;
			}
		}
		$res = model('User/User')->checkKey($val, $key);
		if ($res) {
			echo '{"info":"通过信息验证","status":"y"}';
		} else {
			if ($this->_post('name') == 'mobile_phone') {
				$mes = '手机号码已存在';
			} elseif ($this->_post('name') == 'email') {
				$mes = '邮箱已存在';
			} elseif ($this->_post('name') == 'username') {
				$mes = '用户名存在';
			}
			echo '{"info":"' . $mes . '","status":"n"}';
		}
	}
   /**
	* 
	* 验证通过 生成cookie 或session
	* @param  $arr 用户信息
	* @author wj
	* @date 2014-10-13
	*/
	private function putlogin($uid, $uname) {
		if (empty($uid)) {
			return FALSE;
		}
		cookie('_uname', $uname);
		cookie('user_key', authcode($uid, 'ENCODE', C('site_key')));
		$data['last_session'] = session_id();
		model('User')->where('id='.$uid.'')->save($data);
		return true;
	}
}